<template>
  <div class="network-test">
    <van-nav-bar title="网络测试" left-arrow @click-left="$router.back()" />
    
    <div class="test-content">
      <van-cell-group title="网络连接测试">
        <van-cell title="API服务器地址" :value="apiUrl" />
        <van-cell title="网络状态" :value="networkStatus" />
        <van-cell title="测试结果" :value="testResult" />
      </van-cell-group>
      
      <div class="test-buttons">
        <van-button 
          type="primary" 
          size="large" 
          @click="testNetworkConnection"
          :loading="testing"
          block
        >
          测试网络连接
        </van-button>
        
        <van-button 
          type="success" 
          size="large" 
          @click="testAPIConnection"
          :loading="apiTesting"
          block
        >
          测试API连接
        </van-button>
        
        <van-button 
          type="warning" 
          size="large" 
          @click="testLoginAPI"
          :loading="loginTesting"
          block
        >
          测试登录API
        </van-button>
        
        <van-button 
          type="default" 
          size="large" 
          @click="diagnoseNetwork"
          block
        >
          🔍 网络诊断
        </van-button>
        
        <van-button 
          type="info" 
          size="large" 
          @click="simpleConnectionTest"
          block
        >
          ✅ 简单连接测试
        </van-button>
        
        <van-button 
          type="primary" 
          size="large" 
          @click="androidConnectionTest"
          block
        >
          📱 Android连接测试
        </van-button>
      </div>
      
      <div class="test-logs" v-if="logs.length > 0">
        <van-cell-group title="测试日志">
          <van-cell 
            v-for="(log, index) in logs" 
            :key="index"
            :title="log.time"
            :value="log.message"
            :label="log.details"
          />
        </van-cell-group>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { showToast, showSuccessToast, showFailToast } from 'vant'
import { BASE_URL } from '@/config/api'
import api from '@/api/auth'

const apiUrl = ref(BASE_URL)
const networkStatus = ref('未知')
const testResult = ref('未测试')
const testing = ref(false)
const apiTesting = ref(false)
const loginTesting = ref(false)
const logs = ref([])

const addLog = (message, details = '') => {
  logs.value.unshift({
    time: new Date().toLocaleTimeString(),
    message,
    details
  })
  if (logs.value.length > 10) {
    logs.value.pop()
  }
}

// 测试基本网络连接
const testNetworkConnection = async () => {
  testing.value = true
  addLog('开始测试网络连接...')
  
  try {
    // 测试是否能访问外网 - 使用更简单的方法
    const response = await fetch('https://httpbin.org/get', {
      method: 'GET',
      mode: 'cors',
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    if (response.ok) {
      networkStatus.value = '已连接'
      testResult.value = '网络连接正常'
      addLog('网络连接测试成功', '可以访问外网')
      showSuccessToast('网络连接正常')
    } else {
      throw new Error(`HTTP ${response.status}`)
    }
  } catch (error) {
    networkStatus.value = '连接失败'
    testResult.value = '网络连接失败'
    addLog('网络连接测试失败', error.message)
    showFailToast('网络连接失败')
  } finally {
    testing.value = false
  }
}

// 测试API服务器连接
const testAPIConnection = async () => {
  apiTesting.value = true
  addLog('开始测试API服务器连接...')
  
  try {
    // 测试API服务器根路径
    const response = await api.get('/')
    
    addLog('API服务器连接成功', `状态码: ${response.status || 'OK'}`)
    showSuccessToast('API服务器连接成功')
  } catch (error) {
    // 如果根路径失败，尝试测试登录接口
    try {
      addLog('根路径失败，尝试测试登录接口...')
      const loginResponse = await api.post('/login/login', {
        username: 'test',
        password: 'test',
        type: 1
      })
      addLog('登录接口测试成功', 'API服务器可访问')
      showSuccessToast('API服务器连接成功')
    } catch (loginError) {
      addLog('API服务器连接失败', loginError.message)
      showFailToast('API服务器连接失败')
    }
  } finally {
    apiTesting.value = false
  }
}

// 测试登录API
const testLoginAPI = async () => {
  loginTesting.value = true
  addLog('开始测试登录API...')
  
  try {
    const response = await api.post('/login/login', {
      username: 'test',
      password: 'test',
      type: 1
    })
    
    addLog('登录API测试成功', 'API响应正常')
    showSuccessToast('登录API测试成功')
  } catch (error) {
    addLog('登录API测试失败', error.message)
    showFailToast('登录API测试失败')
  } finally {
    loginTesting.value = false
  }
}

// 网络诊断功能
const diagnoseNetwork = async () => {
  addLog('开始网络诊断...')
  
  // 1. 检查API配置
  addLog('检查API配置', `Base URL: ${apiUrl.value}`)
  
  // 2. 检查网络状态
  if (navigator.onLine) {
    addLog('网络状态', '设备已连接网络')
  } else {
    addLog('网络状态', '设备未连接网络')
  }
  
  // 3. 检查用户代理
  addLog('用户代理', navigator.userAgent)
  
  // 4. 检查是否在移动环境
  const isMobile = /Android|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
  addLog('设备类型', isMobile ? '移动设备' : '桌面设备')
  
  // 5. 尝试ping API服务器
  try {
    addLog('尝试ping API服务器...')
    const startTime = Date.now()
    const response = await fetch(apiUrl.value, {
      method: 'HEAD',
      mode: 'no-cors'
    })
    const endTime = Date.now()
    addLog('Ping结果', `响应时间: ${endTime - startTime}ms`)
  } catch (error) {
    addLog('Ping失败', error.message)
  }
  
  // 6. 检查CORS
  try {
    addLog('检查CORS支持...')
    const response = await fetch(apiUrl.value, {
      method: 'GET',
      mode: 'cors'
    })
    addLog('CORS检查', '支持CORS')
  } catch (error) {
    addLog('CORS检查', `不支持CORS: ${error.message}`)
  }
  
  showSuccessToast('网络诊断完成')
}

// 简单连接测试
const simpleConnectionTest = async () => {
  addLog('开始简单连接测试...')
  
  try {
    // 在Android环境中，使用axios而不是fetch
    const response = await api.get('/login/getPhoneVerifyCode', {
      params: {
        loginPhone: '13800138000'
      },
      timeout: 5000
    })
    
    addLog('简单连接测试成功', 'API服务器响应正常')
    showSuccessToast('连接测试成功！API服务器正常')
    
    // 更新状态
    networkStatus.value = '已连接'
    testResult.value = '连接正常'
    
  } catch (error) {
    // 如果验证码接口失败，尝试其他方法
    try {
      addLog('验证码接口失败，尝试其他测试方法...')
      
      // 尝试一个更简单的请求
      const response = await api.get('/', {
        timeout: 5000
      })
      
      addLog('简单连接测试成功', 'API服务器响应正常')
      showSuccessToast('连接测试成功！API服务器正常')
      
      // 更新状态
      networkStatus.value = '已连接'
      testResult.value = '连接正常'
      
    } catch (secondError) {
      addLog('简单连接测试失败', secondError.message)
      showFailToast('连接测试失败')
      
      // 更新状态
      networkStatus.value = '连接失败'
      testResult.value = '连接失败'
    }
  }
}

// Android专用连接测试
const androidConnectionTest = async () => {
  addLog('开始Android连接测试...')
  
  try {
    // 检测是否在Android环境
    const isAndroid = /Android/i.test(navigator.userAgent)
    addLog('设备检测', isAndroid ? 'Android设备' : '非Android设备')
    
    // 使用axios进行连接测试，这是最可靠的方法
    const response = await api.post('/login/login', {
      username: 'LSY003', // 使用您之前测试成功的用户名
      password: 'test123', // 使用测试密码
      type: 1
    })
    
    addLog('Android连接测试成功', 'API服务器响应正常')
    showSuccessToast('Android连接测试成功！')
    
    // 更新状态
    networkStatus.value = '已连接'
    testResult.value = '连接正常'
    
  } catch (error) {
    // 如果登录失败，但能收到响应，说明网络连接是正常的
    if (error.response) {
      addLog('Android连接测试成功', `服务器响应正常 (状态码: ${error.response.status})`)
      showSuccessToast('Android连接测试成功！服务器可访问')
      
      // 更新状态
      networkStatus.value = '已连接'
      testResult.value = '连接正常'
    } else {
      addLog('Android连接测试失败', error.message)
      showFailToast('Android连接测试失败')
      
      // 更新状态
      networkStatus.value = '连接失败'
      testResult.value = '连接失败'
    }
  }
}

onMounted(() => {
  addLog('网络测试页面已加载', `API地址: ${apiUrl.value}`)
})
</script>

<style scoped>
.network-test {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.test-content {
  padding: 16px;
}

.test-buttons {
  margin: 20px 0;
}

.test-buttons .van-button {
  margin-bottom: 12px;
}

.test-logs {
  margin-top: 20px;
}
</style>
